package com.meng.redis.thread;

import com.meng.model.PointOfSale;
import com.meng.redis.enumeration.RedisKeyAndSaveDataServiceNameEnum;
import com.meng.service.inter.PointOfSaleService;
import com.meng.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.lang.reflect.Field;
import java.util.List;


/**
 * 同步redis数据到Mysql
 *
 * @author MENG
 * @version 2018/4/12
 * @see
 */
public class SyncRedisDataToMysqlThread implements Runnable
{
    private Logger logger = LoggerFactory.getLogger(PointOfSale.class);

    @Override
    public void run()
    {
        try
        {
            RedisTemplate redisTemplate = (RedisTemplate)SpringContextUtils.getBean("redisTemplate");

            ListOperations listOperations = redisTemplate.opsForList();

            Field[] fields = RedisKeyAndSaveDataServiceNameEnum.class.getFields();

            for (Field field : fields)
            {
                RedisKeyAndSaveDataServiceNameEnum redisKeyAndSaveDataServiceNameEnum = RedisKeyAndSaveDataServiceNameEnum.valueOf(field.getName());

                List<PointOfSale> list = listOperations.range(redisKeyAndSaveDataServiceNameEnum.getRedisKey(),0,-1);

                PointOfSaleService pointOfSaleService = (PointOfSaleService)SpringContextUtils.getBean(redisKeyAndSaveDataServiceNameEnum.getServiceName());

                pointOfSaleService.insert(list);

                redisTemplate.delete(redisKeyAndSaveDataServiceNameEnum.getRedisKey());//清空数据
            }
        }
        catch (Exception e)
        {
            logger.error("定时同步Redis数据到Mysql执行异常!!!",e);
        }
    }
}
